package dup.login.demo.service.impl;

import dup.login.demo.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("fileSeriviceImpl")
public class FileSeriviceImpl implements FileService {
    @Value(value = "${dup.uploadfile.filepath}")
    private String filePath;

    @Value(value = "${dup.uploadfile.virtualpath}")
    private String virtualPath;

    private String getDate() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormat = simpleDateFormat.format(date);
        return dateFormat;
    }

    @Override
    public String uploadFile(MultipartFile file, String category) {
        if (file.isEmpty()) {
            throw new RuntimeException("您上传的文件不存在！");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重命名文件名
        fileName = UUID.randomUUID() + suffixName;
        // 获取文件全路径
        String dir = filePath + '/' + category + '/' + getDate() + '/' + fileName;
        File dest = new File(dir);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return virtualPath + '/' + category + '/' + getDate() + '/' + fileName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败！");
        }
    }

    @Override
    public ArrayList<String> uploadMultipartFile(List<MultipartFile> files, String category) {
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        ArrayList<String> dirList = new ArrayList<>();
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 获取文件的后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                // 重命名文件名
                fileName = UUID.randomUUID() + suffixName;
                // 获取文件全路径
                String dir = filePath + '/' + category + '/' + getDate() + '/' + fileName;
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(dir)));
                    stream.write(bytes);
                    stream.close();
                    dirList.add(virtualPath + '/' + category + '/' + getDate() + '/' + fileName);
                } catch (Exception e) {
                    stream = null;
                    throw new RuntimeException("第" + i + "个文件上传失败！");
                }
            } else {
                throw new RuntimeException("第" + i + "个文件不存在！");
            }
        }
        return dirList;
    }

    @Override
    public void downloadFile(String fileDir, HttpServletResponse response) {
        if (fileDir != null) {
            String fileName = fileDir.substring(fileDir.lastIndexOf("/") + 1);
            String path = fileDir.substring(virtualPath.getBytes().length);
            String realPath = filePath + path;
            File file = new File(realPath);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("文件下载失败！");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                           // e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                           // e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
